
import os
import pymysql
from loguru import logger
import allure
from utils.handle_path import CONFIG_DIR
from utils.base_api import BaseApi


class HandleMysql:
    @allure.step('step:连接数据库')
    def __init__(self, **kwargs):
        # 连接到数据库
        try:
            self.con = pymysql.connect(charset="utf8", **kwargs)
        except Exception as e:
            logger.error(f'数据库连接失败，连接参数：{kwargs}')
            raise e
        else:
            # 创建一个游标
            self.cur = self.con.cursor()

    def get_one(self, sql):
        """获取查询到的第一条数据"""
        self.con.commit()
        self.cur.execute(sql)
        return self.cur.fetchone()

    def get_all(self, sql):
        """获取sql语句查询到的所有数据"""
        self.con.commit()
        self.cur.execute(sql)
        return self.cur.fetchall()

    def count(self, sql):
        """获取sql语句查询到的数量"""
        self.con.commit()
        res = self.cur.execute(sql)
        return res

    def close(self):
        # 关闭游标对象
        self.cur.close()
        # 断开连接
        self.con.close()


if __name__ == '__main__':
    p = os.path.join(CONFIG_DIR, 'config.yaml')
    print(p)
    a = BaseApi()
    conf = a.get_yaml(p)
    mysql = conf['mysql']
    print(mysql)
    db = HandleMysql(**mysql)
    print(type(db))
    print(db)
    x = db.get_one('SELECT * from czt_testing.pm_picture where platform = "RF123"')
    print(x)